﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using EduFormManager.Models;
using EduFormManager.Models.Repo;

namespace EduFormManager.Forms.UserControls
{
    public partial class XtraDictionaryEditEduControl : XtraBaseControl
    {
        private EduOrg m_edu;
        private XtraDictionaryEduControl m_eduControl;

        public XtraDictionaryEditEduControl()
        {
            InitializeComponent();

            this.labelError.Text = string.Empty;

            Init();
        }

        public XtraDictionaryEditEduControl(XtraDictionaryEduControl parentEduControl = null)
        {
            InitializeComponent();

            this.m_eduControl = parentEduControl;

            Init();
        }

        private void Init()
        {
            this.labelError.Text = string.Empty;
            this.ControlType = Type.Component;
        }

        public override Type ControlType
        {
            get
            {
                return base._controlType;
            }
            set
            {
                this.buttonOk.Visible = (value == Type.Form);
                this.buttonCancel.Visible = (value == Type.Form);
                base._controlType = value;
            }
        }

        public XtraDictionaryEduControl ParentEduControl
        {
            set
            {
                this.m_eduControl = value;
            }
            get
            {
                return this.m_eduControl;
            }
        }

        public BindingSource EduOrgKindBinding
        {
            set
            {
                this.eduOrgKindBindingSource = value;
            }
        }

        public BindingSource MunicipalityBinding
        {
            set
            {
                this.municipalityBindingSource = value;
            }
        }

        public IList<EduOrgKind> DataSourceEduOrgKind
        {
            set
            {
                this.eduOrgKindBindingSource.DataSource = value;
            }
        }

        public override IList<Municipality> DataSourceMunicipality
        {
            set
            {
                this.municipalityBindingSource.DataSource = value;
            }
        }

        public EduOrg Edu
        {
            set
            {
                if (value == null)
                    return;
                this.m_edu = value;
                this.comboBoxMunit.SelectedItem = m_edu.Municipality;
                this.comboBoxEduKind.SelectedItem = m_edu.Kind;

                this.textBoxDictEduName.Text = m_edu.Name;
                this.textBoxDictEduOperator.Text= m_edu.Operator;
                this.textBoxDictEduShortname.Text = m_edu.ShortName;

                Credentials cred = RepoHelper.Repo.GetCredentials(m_edu.Id, Credentials.Type.Edu);
                this.textBoxDictLogin.Text = cred != null ? cred.Login : string.Empty;
                this.textBoxDictPassword.Text = cred != null ? cred.Password : string.Empty;
                this.textBoxDictPasswordRepeated.Text = cred != null ? cred.Password : string.Empty;
            }
            get
            {
                return m_edu;
            }
        }

        public EduOrg Save()
        {
            m_edu.Municipality = (Municipality)comboBoxMunit.SelectedItem;
            m_edu.Kind = (EduOrgKind)comboBoxEduKind.SelectedItem;

            m_edu.Name = this.textBoxDictEduName.Text.Trim();
            m_edu.ShortName = this.textBoxDictEduShortname.Text.Trim();
            m_edu.Operator = this.textBoxDictEduOperator.Text.Trim();

            RepoHelper.Repo.Save(m_edu);

            if (!string.IsNullOrEmpty(this.textBoxDictLogin.Text.Trim()))
            {
                Credentials cred = RepoHelper.Repo.GetCredentials(m_edu.Id, Credentials.Type.Edu);
                if (cred == null)
                {
                    cred = new Credentials();
                    cred.ReferenceID = m_edu.Id;
                    cred.LoginType = Credentials.Type.Edu;
                }
                cred.Login = this.textBoxDictLogin.Text.Trim();
                cred.Password = this.textBoxDictPassword.Text.Trim();
                RepoHelper.Repo.Save(cred);
            }

            this.labelError.Text = string.Empty;
            return m_edu;
        }

        public bool CanSave()
        {
            string eduName = this.textBoxDictEduName.Text.Trim();
            string eduShortName = this.textBoxDictEduShortname.Text.Trim();
            bool isEduExist = (RepoHelper.Repo.GetEduOrgByName(eduName) != null && eduName != m_edu.Name) ||
                (RepoHelper.Repo.GetEduOrgByShortname(eduShortName) != null && eduShortName != m_edu.ShortName);
            if (isEduExist)
            {
                this.labelError.Text = "ОУ с таким именем уже существует";
                return false;
            }
            bool isFieldsOk = comboBoxEduKind.SelectedItem != null &&
                comboBoxMunit.SelectedItem != null &&
                !string.IsNullOrEmpty(eduName) &&
                !string.IsNullOrEmpty(eduShortName);
            if (!isFieldsOk)
            {
                this.labelError.Text = "Проверьте все ли поля заполнены";
                return false;
            }
            string login = this.textBoxDictLogin.Text.Trim();
            string password = this.textBoxDictPassword.Text.Trim();
            if (!string.IsNullOrEmpty(login))
            {
                Credentials cred = RepoHelper.Repo.GetCredentials(m_edu.Id, Credentials.Type.Edu);
                Credentials cred_dub = RepoHelper.Repo.GetCredentials(login);
                bool isCredentialsExist = cred == null ? cred_dub != null : 
                    cred_dub != null ? (cred.ReferenceID != cred_dub.ReferenceID || cred.LoginType != cred_dub.LoginType) : false;
                if (isCredentialsExist)
                {
                    this.labelError.Text = "Такой логин уже существует";
                    return false;
                }
                if (string.IsNullOrEmpty(password))
                {
                    this.labelError.Text = "Пароль не может быть пустым";
                    return false;
                }
                if (password != this.textBoxDictPasswordRepeated.Text.Trim())
                {
                    this.labelError.Text = "Пароли не совпадают";
                    return false;
                }
            }
            return true;
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            if (this.CanSave())
            {
                EduOrg edu = this.Save();
                if (m_eduControl != null)
                {
                    m_eduControl.RebuildEduTree();
                    m_eduControl.SelectEdu(edu);
                }
                this.ParentForm.Close();
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            m_eduControl.CancelNew();
            if (this.ParentForm != null)
                this.ParentForm.Close();
        }
    }
}
